<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var A = [
        [1, 2, 3, 4, 5],
        [16, 17, 18, 19, 6],
        [15, 24, 25, 20, 7],
        [14, 23, 22, 21, 8],
        [13, 12, 11, 10, 9],
      ];

      function spiralTraverse(matrix) {
        const result = [];
        let top = 0;
        let bottom = matrix.length - 1;
        let left = 0;
        let right = matrix[0].length - 1;

        // 从左到右
        while (top <= bottom && left <= right) {
          // 从左到右
          debugger;
          for (let i = left; i <= right; i++) {
            result.push(matrix[top][i]);
          }
          top++;

          // 从上到下
          for (let i = top; i <= bottom; i++) {
            result.push(matrix[i][right]);
          }
          right--;

          // 检查是否还需要继续遍历
          if (top > bottom || left > right) {
            break;
          }

          // 从右到左遍历底部
          for (let i = right; i >= left; i--) {
            result.push(matrix[bottom][i]);
          }
          bottom--;

          // 从下往上遍历左边
          for (let i = bottom; i >= top; i--) {
            result.push(matrix[i][left]);
          }
          left++;
        }
        return result.join(",");
      }

      console.log(spiralTraverse(A));
    </script>
  </body>
</html>
